package com.moyu.crowdsource.social;

import javax.sql.DataSource;

import com.moyu.crowdsource.entity.AccountUser;
import com.moyu.crowdsource.websetting.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurer;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.security.SpringSocialConfigurer;

@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter  implements SocialConfigurer {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        return new JdbcUsersConnectionRepository(dataSource,connectionFactoryLocator,Encryptors.noOpText());//加解密后期需改
    }

    @Override
    public UserIdSource getUserIdSource() {
        return () -> {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication.getPrincipal() instanceof AccountUser)
                return ((AccountUser) authentication.getPrincipal()).getAccountUsername();
            return authentication.getName();
        };
    }


    @Bean
    public SpringSocialConfigurer moyuSocialSecurityConfig(){
        String filterProcessesUrl=securityProperties.getMySocialProperties().getFilterProcessesUrl();
        MoyuSpringSocialConfigurer configurer=new MoyuSpringSocialConfigurer(filterProcessesUrl);
        return  configurer;
    }
}
